﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;

namespace S3.Common
{
    public class Utils
    {
        public static void DoPrint(PrintDataObject printDataObject)
        {
            try
            {
                string filePrintTemplate = Environment.CurrentDirectory + "\\" + Constants.PrintFileTemplate;// "\\PrintTemplate.htm";
                if (File.Exists(filePrintTemplate))
                {
                    string newRowHtmlFormat = Constants.PrintRowHtmlFormat;// @"<tr><td valign=top>{0}</td><td valign=top>{1}</td><td valign=top>{2}</td><td valign=top>{3}</td></tr>";
                    StringBuilder str = new StringBuilder();


                    foreach (PrintSoldItems item in printDataObject.ListPrintSoldItems)
                    {
                        String[] strTemp = { item.Name, item.Qty, item.Price, item.SubTotal };
                        str.AppendFormat(newRowHtmlFormat, strTemp);
                    }

                    var printContent = "";
                    using (StreamReader reader = new StreamReader(filePrintTemplate))
                    {
                        printContent = reader.ReadToEnd();
                    }

                    printContent = printContent.Replace(Constants.PrintDataToPrint, str.ToString());
                    printContent = printContent.Replace(Constants.PrintCustNo, printDataObject.CustomerID);
                    printContent = printContent.Replace(Constants.PrintInvoiceNo, printDataObject.InvoiceID);
                    printContent = printContent.Replace(Constants.PrintTotalMoney, printDataObject.TotalMoney);
                    printContent = printContent.Replace(Constants.PrintDiscount, printDataObject.Discount);
                    printContent = printContent.Replace(Constants.PrintDeskName, printDataObject.TimingServiceName);
                    printContent = printContent.Replace(Constants.PrintStartTime, printDataObject.StartTime);
                    printContent = printContent.Replace(Constants.PrintEndTime, printDataObject.EndTime);
                    printContent = printContent.Replace(Constants.PrintPaid, printDataObject.Paid);

                    string filePrintMe = Environment.CurrentDirectory + "\\" + Constants.PrintFilePrintMe;

                    File.WriteAllText(filePrintMe, printContent);

                    var p = new ProcessStartInfo();
                    p.Verb = "print";
                    p.WindowStyle = ProcessWindowStyle.Hidden;
                    p.FileName = filePrintMe;
                    p.UseShellExecute = true;
                    System.Diagnostics.Process.Start(p);
                }
                else
                {
                    
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Loi in hoa don. " + ex.Message);                
            }
        }

        public static string InvoiceNoGenerating()
        {
            return string.Format("{0:yyMMddhhmmss}", DateTime.Now);            
        }

        public static string FormatNotesMessage(string[] inputParam, NotesType type)
        {
            StringBuilder str = new StringBuilder();
            str.Append("[");
            str.Append(string.Format(Constants.Format_Date_Time, DateTime.Now));
            str.Append("] - ");
            
            
            switch (type)
            {
                case NotesType.TimingServiceChangeType:
                    str.AppendFormat(Constants.MsgTimingServiceChangeType, inputParam);
                    break;
                case NotesType.TimingServiceUsedServices:
                    str.AppendFormat(Constants.MsgTimingServiceUsedServices, inputParam);
                    break;
                case NotesType.TimingServiceReceivedMoney:
                    str.AppendFormat(Constants.MsgTimingServiceReceivedMoney, inputParam);
                    break;
                case NotesType.TimingServiceTransferedMoney:
                    str.AppendFormat(Constants.MsgTimingServiceTransferedMoney, inputParam);
                    break;
                case NotesType.TimingServiceChangeDesk:
                    str.AppendFormat(Constants.MsgTimingServiceChangeDesk, inputParam);
                    break;
            }

            str.AppendLine();

            return str.ToString();
        }
    

        public static decimal RoundMoneyTo500Vnd(decimal money)
        {
            if (money != 0)
            {
                decimal tempTotal = money / 1000;
                decimal tempTotalFloor = Math.Floor(tempTotal);
                decimal dec = Math.Abs(tempTotal - tempTotalFloor);

                dec = dec * 1000;
                tempTotalFloor = tempTotalFloor * 1000;

                if (dec > 0 && dec < 250)
                {
                    dec = 0;
                }
                else if ((dec >= 250 && dec < 500) || (dec > 500 && dec < 750))
                {
                    dec = 500;
                }
                else if (dec >= 750)
                {
                    dec = 1000;
                }

                return tempTotalFloor + dec;
            }

            return 0;
        }

        public static string Lisence(string input)
        {
            var temp = Encrypt(input);
            if (temp != string.Empty)
            {
                var count4 = 0;
                StringBuilder output = new StringBuilder();
                for (int i = 0; i < temp.Length; i++)
                {
                    output.Append(temp[i]);
                    count4 = count4 + 1;

                    if (count4 == 4 && i != (temp.Length - 1))
                    {
                        output.Append("-");
                        count4 = 0;
                    }
                }

                return output.ToString();
            }

            return "";
        }

        public static string Encrypt(string mess)
        {
            MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(mess);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString().ToUpper();
        }

        public static string[] KindOfMachinesList()
        {
            string[] returnValue = {};
            var values = Constants.KindOfMachines;
            if (values != null)
            {
                returnValue = values.ToString().TrimEnd(',').Split(',');                
            }
            return returnValue;

        }

        public static string StringFormatMoney(decimal decInput)
        {
            var intAccuracy = Constants.NumberOfMoneyAccuracy;
            string format = "{0:###,##0";
            for (int i = 0; i < intAccuracy; i++)
            {
                format += "0";
            }
            format += "}";

            //Make round            
            decInput = Math.Round(decInput);            
            
            return string.Format(format, decInput);

        }

        //Chuyen so thanh chu
        public static string DocSo(decimal input)
        {
            string returnValue = "";
            //Loai bo phan thap phan
            string s = Math.Floor(input).ToString();
            if (s != "")
            {
                s = XoaSoKhong(s);
                switch (s.Length)
                {
                    case 1: returnValue = MotSo(s) + " đồng"; break;
                    case 2: returnValue = HaiSo(s) + " đồng"; break;
                    case 3: returnValue = BaSo(s) + " đồng"; break;
                    default: returnValue = NhieuSo(s, s.Length); break;
                }
            }
                        
            return "(" + returnValue.Trim().Replace("  ", " ") + ")";
        }

        #region Các hàm đọc số
        private static string MotSo(string bienso)
        {
            switch (bienso)
            {
                case "0": return "không";
                case "1": return "một";
                case "2": return "hai";
                case "3": return "ba";
                case "4": return "bốn";
                case "5": return "năm";
                case "6": return "sáu";
                case "7": return "bảy";
                case "8": return "tám";
                case "9": return "chín";
            }
            return "không";
        }

        private static string HaiSo(string bienso)
        {
            string biendoc = " mười ";

            if ((bienso.Substring(1, 1) == "0") && (bienso.Substring(0, 1)
            != "1")) biendoc = MotSo(bienso.Substring(0, 1)) + " mươi ";
            if (bienso.Substring(1, 1) != "0")
                switch (bienso.Substring(1, 1))
                {
                    case "5":
                        if (bienso.Substring(0, 1) == "1") biendoc = " mười lăm";
                        else biendoc = MotSo(bienso.Substring(0, 1)) + " mươi lăm";
                        break;
                    case "1":
                        if (bienso.Substring(0, 1) == "1") biendoc = " mười một";
                        else biendoc = MotSo(bienso.Substring(0, 1)) + " mươi mốt";
                        break;
                    default:
                        if (bienso.Substring(0, 1) == "1") biendoc = " mười " + MotSo(bienso.Substring(1, 1));
                        else biendoc = MotSo(bienso.Substring(0, 1)) + " mươi " + MotSo(bienso.Substring(1, 1));
                        break;
                }
            return biendoc;
        }

        private static string BaSo(string bienso)
        {
            string biendoc = "trăm";
            if (bienso.Substring(1, 1) == "0")
            {
                if (bienso.Substring(2, 1) == "0") biendoc = MotSo(bienso.Substring(0, 1)) + " trăm ";
                else biendoc = MotSo(bienso.Substring(0, 1)) + " trăm lẻ " + MotSo(bienso.Substring(2, 1));
            }
            else
            {
                biendoc = MotSo(bienso.Substring(0, 1)) + " trăm " + HaiSo(bienso.Substring(1, 2));
            }
            return biendoc;
        }
        #endregion
        // hàm xử lý vấn đề số 0
        private static string XoaSoKhong(string tam)
        {
            while (tam[0] == '0')
            {
                if (tam.Length > 1) tam = tam.Substring(1, tam.Length - 1);
                else break;
            }
            return tam;
        }
        // hàm xử lý chèn các giá trị
        private static string KieuChen(int tam)
        {
            switch (tam)
            {
                case 0: return " đồng ";
                case 1: return " nghìn ";
                case 2: return " triệu ";
                case 3: return " tỷ ";
            }
            return "";
        }
        // hàm đọc nhiều số
        private static string NhieuSo(string bienso, int dodai)
        {
            string biendoc = "", bientam = "";
            int i = 0;
            while ((dodai) > 3)
            {
                bientam = BaSo(bienso.Substring(bienso.Length - 3, 3));
                bienso = bienso.Substring(0, bienso.Length - 3);
                biendoc = bientam + KieuChen(i) + biendoc;
                i++;
                if (i > 3) i = 1;
                if (dodai > 3) dodai = dodai - 3;
            }
            if (dodai == 1) biendoc = MotSo(bienso) + KieuChen(i) + biendoc;
            if (dodai == 2) biendoc = HaiSo(bienso) + KieuChen(i) + biendoc;
            if (dodai == 3) biendoc = BaSo(bienso) + KieuChen(i) + biendoc;
            return biendoc;
        }

    }
}
